<template>
  <el-dialog :close-on-click-modal="false" :title="form.dataId ? $t('common.detailBtn') : $t('common.editBtn')" width="1000"
             draggable v-model="visible">
    <el-form :model="form" :rules="dataRules" label-width="120px" ref="dataFormRef" v-loading="loading">
      <el-form-item :label="$t('config.dataId')" prop="dataId">
        <el-input :placeholder="$t('config.dataId')" v-model="form.dataId" disabled/>
      </el-form-item>
      <el-form-item :label="$t('config.group')" prop="group">
        <el-input :placeholder="$t('config.group')" v-model="form.group" disabled/>
      </el-form-item>
        <el-form-item :label="$t('config.content')" prop="content">
              <code-editor v-model="form.content" theme="darcula" height="500" mode="go" style="width: 100%;"></code-editor>
        </el-form-item>
    </el-form>
    <template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button @click="onSubmit" type="primary" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
    </template>
  </el-dialog>
</template>

<script lang="ts" name="config-detail" setup>
  import {useMessage} from '/@/hooks/message';
  import { getObj, update} from '/@/api/admin/config';
  import {useI18n} from 'vue-i18n';
  const CodeEditor = defineAsyncComponent(() => import('/@/components/CodeEditor/index.vue'));
  // 定义子组件向父组件传值/事件
  const emit = defineEmits(['refresh']);

  const {t} = useI18n();

  // 定义变量内容
  const dataFormRef = ref();
  const visible = ref(false);
  const loading = ref(false);


  // 提交表单数据
  const form = reactive({
    dataId: '',
    group:'',
    content: ''
  });

  // 打开弹窗
  const openDialog = (row: any) => {
    visible.value = true;
    form.dataId = '';
    // 重置表单数据
    nextTick(() => {
      dataFormRef.value?.resetFields();
    });

    // 获取sysOauthconfigDetails信息
    if (row.dataId) {
      form.dataId = row.dataId;
      getsysOauthconfigDetailsData(row);
    }
  };

  // 提交
  const onSubmit = async () => {
    try {
      loading.value = true;
      update(form).then((res: any) => {
          console.log(res.data);
        if(res.data==true){
          useMessage().success(t(form.dataId ? 'common.editSuccessText' : 'common.addSuccessText'));
          visible.value = false;
          emit('refresh');
        }else{
          useMessage().error("修改失败");
        }
      });
    } catch (err: any) {
      useMessage().error(err.msg);
    } finally {
      loading.value = false;
    }
  };

  // 初始化表单数据
  const getsysOauthconfigDetailsData = (row: any) => {
    // 获取数据
      console.log(row);
    getObj(row.dataId).then((res: any) => {
      Object.assign(form, res.data);
      console.log(res.data)
    });
  };

  // 暴露变量
  defineExpose({
    openDialog,
  });
</script>
